package com.atsmart.app.activity;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.ActivityManager.MemoryInfo;
import android.app.AlertDialog.Builder;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.format.Formatter;
import android.text.method.DigitsKeyListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.activity.ProductListActivity.Item;
import com.atsmart.app.adapter.AutoCompleteAdapter;
import com.atsmart.app.adapter.ProAutoCompleteAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.http.HttpHelper;
import com.atsmart.app.model.ClientInfo;
import com.atsmart.app.model.ClientListInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.ContextInfo;
import com.atsmart.app.model.LocationPageinfo;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.ProductInfo;
import com.atsmart.app.model.ProductItemInfo;
import com.atsmart.app.model.ProductItemListInfo;
import com.atsmart.app.model.ProductListInfo;
import com.atsmart.app.model.ReportHistoryInfo;
import com.atsmart.app.model.ResultInfo;
import com.atsmart.app.model.TemplateDetailInfo;
import com.atsmart.app.model.TemplateItemInfo;
import com.atsmart.app.model.TempleteSelectListInfo;
import com.atsmart.app.model.UploadInfo;
import com.atsmart.app.model.UploadItemInfo;
import com.atsmart.app.sql.ClientSqlHelper;
import com.atsmart.app.sql.ContextSqlHelper;
import com.atsmart.app.sql.ProductItemSqlHelper;
import com.atsmart.app.sql.ProductSqlHelper;
import com.atsmart.app.sql.SelectInfoSql;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.sql.TaskInfoSqlHelper;
import com.atsmart.app.sql.TaskNumSqlHelper;
import com.atsmart.app.sql.TempFromTaskSql;
import com.atsmart.app.sql.TemplateDetailSql;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.view.MyAutoCompleteTextView;
import com.atsmart.app.view.ProMyAutoCompleteTextView;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.google.json.annotations.SerializedName;
import com.google.zxing.BarcodeFormat;

/* 1  swith 加载 模版效率
 * 2  获得客户的信息耗时 ，缓存
 *   
 */

public class ReportActivity extends BaseActivity {
	Builder builder;
	private boolean isUpBtn = false;
	public static final String TAG = ReportActivity.class.getName();
	private static final int CAMERA_WITH_DATA = 3023;
	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/atsmart/CameraCache");
	private static File mCurrentPhotoFile;// 照相机拍照得到的图片
	Uri imgUri;
	private static Bundle bundle;

	ImageView chooseimage;
	Boolean NLOC = true;
	//TODO 汇报类型
	private static final int ITEM_TYPE_TEXTVIEW = 1;
	private static final int ITEM_TYPE_EDITVIEW = 2;
	private static final int ITEM_TYPE_CHECKBOX = 3;
	private static final int ITEM_TYPE_IMAGEVIEW = 4;
	private static final int ITEM_TYPE_NUMBERIC = 5;
	private static final int ITEM_TYPE_SELECT = 6;
	private static final int ITEM_TYPE_RECORD = 7;
	private static final int ITEM_TYPE_VIDEO = 8;
	private static final int ITEM_TYPE_TEXTAREA = 9;
	private static final int ITEM_TYPE_DATE = 10;
	private static final int ITEM_TYPE_TOTAL = 11;
	private static final int ITEM_TYPE_TIME = 12;
	private static final int ITEM_TYPE_POI = 13;
	private static final int ITEM_TYPE_PRODUCT = 14;
	private static final int ITEM_TYPE_CODE = 100;
	private int templateID;
	private String templateName;
	private TemplateDetailInfo detailInfo;
	private LinearLayout rootLayout;
	private Map<Integer, Integer> items;
	private Map<Integer, Integer> flagItems;
	private boolean hasImage;
	private UploadInfo uploadInfo;
	private Gson gson;
	private int vId;
	private int sId;
	private int rId;
	private boolean sf = false;
	private TextView title;
	private int reportType = 0;
	private int polId;
	private int taskId = 0;;
	private String taskTime;
	private String taskName;
	private TemplateDetailSql templateDetailSql = null;
	private ContextSqlHelper csql = null;
	private String capre;
	private long length = 0;
	private long re_length = 0;
	private MediaRecorder recorder;
	private boolean isSDCardExit; // 判断SDCard是否存在
	private File SDPathDir;
	private File tempFile;
	private boolean isStart = false; // 判断SDCard是否存在
	private long time = 0;

	private ProductSqlHelper productSql = null;
	private SelectInfoSql selectInfoSql = null;
	private TempleteSelectListInfo li = null;
	private Map<Integer, String> selects;
	private Map<Integer, TempleteSelectListInfo> Mali;
	private Map<Integer, Integer> totalMap;
//	private TaskInfoSqlHelper tsql = null;

	private EditText showDate111 = null;

	private EditText showTime11 = null;

	private int mYear;

	private int mMonth;

	private int mDay;

	private int mHour;

	private int mMinute;
	private static final int SHOW_DATAPICK = 0;
	private static final int DATE_DIALOG_ID = 1;
	private static final int SHOW_TIMEPICK = 2;
	private static final int TIME_DIALOG_ID = 3;
	private AutoCompleteAdapter adapter;
	private ArrayList<ClientInfo> mOriginalValues = new ArrayList<ClientInfo>();
	private ClientListInfo i = null;
	private int poi_id = -1;
	private ProAutoCompleteAdapter pro_adapter;
	private ArrayList<String> pro_mOriginalValues = new ArrayList<String>();
	private ProductListInfo p = null;
//	private int pro_id = 0;
	private Map<Integer, Integer> proMap = new HashMap<Integer, Integer>();
	private int count = 0;
	/** 是否保存本地标识位 true -- 保存本地 false -- 上传汇报 **/
	private boolean flag11 = false;
	private ClientSqlHelper cssql = null;
	private TaskNumSqlHelper tnsql = null;
	private int bcount = 0;
	private MyAutoCompleteTextView textView = null;
	private int location_flg = 1;
	private Context context;
	private boolean fromTask = false;
	private TempFromTaskSql temSql = null;
	private int screen_width, screen_height;
	private Dialog dialog;
	private ProMyAutoCompleteTextView productEdit = null;
	private int product_edit_item_id = 0;
	private ProductItemSqlHelper isql = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.report_layout);
		context = this;

		builder = new AlertDialog.Builder(this);
		dialog = DialogUtil.getLoadingDialog(context);
		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		screen_height = metrics.heightPixels;
		screen_width = metrics.widthPixels;
		initPopu();
		gson = new Gson();
		items = new HashMap<Integer, Integer>();
		flagItems = new HashMap<Integer, Integer>();
		rootLayout = (LinearLayout) findViewById(R.id.root_layout);

		productSql = new ProductSqlHelper();
		productSql.open(BizApp.getInstance().getSqlHelper());

		templateDetailSql = new TemplateDetailSql();
		templateDetailSql.open(BizApp.getInstance().getSqlHelper());
		csql = new ContextSqlHelper();
		csql.open(BizApp.getInstance().getSqlHelper());
		selectInfoSql = new SelectInfoSql();
		selectInfoSql.open(BizApp.getInstance().getSqlHelper());
		 
		isql = new ProductItemSqlHelper();
		isql.open(BizApp.getInstance().getSqlHelper());
		cssql = new ClientSqlHelper();
		cssql.open(BizApp.getInstance().getSqlHelper());
		tnsql = new TaskNumSqlHelper();
		tnsql.open(BizApp.getInstance().getSqlHelper());

		temSql = new TempFromTaskSql();
		temSql.open(BizApp.getInstance().getSqlHelper());

		BizApp.getInstance().showMemory();
		
		Bundle bundle = getIntent().getExtras();

		if (templateID == 0) {
			templateID = bundle.getInt(PersistentKeyUtil.TEMPLATE_ID_STRING, 0);
			templateName = bundle.getString(PersistentKeyUtil.TEMPLATE_NAME);
			reportType = bundle.getInt(PersistentKeyUtil.REPORT_TYPE, 0);
			location_flg = bundle.getInt(PersistentKeyUtil.LOCATION_FLG, 0);
			if (reportType == 1) {
				taskTime = bundle.getString(PersistentKeyUtil.TASK_TIME);
				taskName = bundle.getString(PersistentKeyUtil.TASK_NAME);
			}
			fromTask = bundle.getBoolean("isFromTask");
			polId = bundle.getInt(PersistentKeyUtil.CLIENT_ID_STRING, 0);
			taskId = bundle.getInt(PersistentKeyUtil.TASK_ID, 0);
			detailInfo = null;
		}
//		Log.e("TAG", "上传位置标志位： = " + location_flg);
		title = (TextView) findViewById(R.id.title);
		title.setText(templateName);
		if (detailInfo != null && detailInfo.getItems() != null
				&& detailInfo.getItems().size() > 0) {
			generateTemplate();
		} else if (templateID == 0) {
			this.finish();
			return;
		} else {
			if (templateDetailSql.getCount(templateID) > 0) {
				getDataFromSql();
			} else {
				if ((BizApp.getInstance().isWiFiActive() || BizApp
						.getInstance().isNetworkAvailable())
						&& BizApp.getInstance().keeping) {
					getTemplate();
				}
			}
		}
		selects = new HashMap<Integer, String>();
		Mali = new HashMap<Integer, TempleteSelectListInfo>();
		totalMap = new HashMap<Integer, Integer>();
		
		PrefsUtils.setReportCodeValue("");
		PrefsUtils.setReportCodeType("");
		PrefsUtils.setReportImagePath("");
		PrefsUtils.setReportRecordPath("");
	}

	private void getDataFromSql() {
		Log.e("TAG", "getData from sql");
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateDetailInfo>() {

			@Override
			protected TemplateDetailInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				if(templateDetailSql != null){
					if(templateDetailSql.getCount(templateID) > 0){
						detailInfo = templateDetailSql.getTemplateInfo(templateID);
					}
				}
				return detailInfo;
			}

			@Override
			protected void runWithResult(TemplateDetailInfo result)
					throws Exception {
				generateTemplate();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(TemplateDetailInfo result,
					int iErrorCode) throws Exception {
				loadingFailed(TAG, iErrorCode);
				
			}
		}.execute();
	}

	private TextView book_notice_text;
	private PopupWindow popupWindow = null;
	private void initPopu(){
		LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View v = mLayoutInflater.inflate(R.layout.popu_layout, null);
		book_notice_text = (TextView) v.findViewById(R.id.cm_log_book_notice);
	    popupWindow = new PopupWindow(v, LayoutParams.WRAP_CONTENT ,LayoutParams.WRAP_CONTENT);
	    popupWindow.setOutsideTouchable(true);
	    popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.setFocusable(true);
		popupWindow.setClippingEnabled(true);
	}
		
		
	@Override
	protected void onResume() {
		super.onResume();
		if (!StringUtil.isEmptyOrNull(PrefsUtils.getClientIdName())) {
			String ClientIdName = PrefsUtils.getClientIdName();
			String[] str1 = ClientIdName.split(",,");
			poi_id = Integer.valueOf(str1[0]);
			if (textView != null) {
				textView.setText(str1[1]);
			}
			PrefsUtils.setClientIdName(null);
		}

		if (hasImage) {
			if (!StringUtil.isEmptyOrNull(PrefsUtils.getReportImagePath())) {
				String[] str = PrefsUtils.getReportImagePath().split(";");
				for (int i = 0; i < str.length; i++) {
					String[] str1 = str[i].split(",");
					Button img = (Button) rootLayout.findViewById(Integer
							.valueOf(str1[0]));
					if (img != null) {
						img.setText("已完成拍照");
					}
				}

			}
		}
		if (capre != null) {
			Button img = (Button) rootLayout.findViewById(Integer.valueOf(vId));
			if (img != null) {
				img.setText("已完成录像");
			}
		}
		if (sf) {
			Button img = (Button) rootLayout.findViewById(Integer.valueOf(sId));
			if (img != null) {
				img.setText("已完成扫描");
			}
		}

	}

	private void getTemplate() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateDetailInfo>() {

			@Override
			protected TemplateDetailInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				TemplateID id = new TemplateID();
				id.id = templateID;
				return ServiceHelper.getInstance().postData(
						ServiceHost.getTemplateDetailURL(), gson.toJson(id),
						TemplateDetailInfo.class);
			}

			@Override
			protected void runWithResult(TemplateDetailInfo result)
					throws Exception {
				if(result != null){
					detailInfo = result;
					if (detailInfo != null && detailInfo.getItems() != null) {
						try {
							templateDetailSql.deleteAttribute(templateID);
						} catch (Exception e) {
						}
						templateDetailSql.addTemplateInfo(detailInfo,
								templateID);
					}
					generateTemplate();
					finishedLoad(TAG);
				} else {
					try{
						getTemplateByUrl2();
					}catch (Exception e) {
					}
				}
			}

			@Override
			protected void runWithError(TemplateDetailInfo result,
					int iErrorCode) throws Exception {
				loadingFailed(TAG, iErrorCode);
				// finish();
				Log.e("TAG", "从服务器获取内容异常");
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					templateDetailSql.deleteAttribute(templateID);
				}catch (Exception e) {
				}
				try{
					getTemplateByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void getTemplateByUrl2() {
		showLoading();
		registerLoadStatus(TAG);
		new ServiceAsynTask<TemplateDetailInfo>() {

			@Override
			protected TemplateDetailInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException, Exception {
				TemplateID id = new TemplateID();
				id.id = templateID;
				return ServiceHelper.getInstance().postData(
						ServiceHost.getTemplateDetailURL(), gson.toJson(id),
						TemplateDetailInfo.class);
			}

			@Override
			protected void runWithResult(TemplateDetailInfo result)
					throws Exception {
				if(result != null){
					detailInfo = result;
					if (detailInfo != null && detailInfo.getItems() != null) {
						try {
							templateDetailSql.deleteAttribute(templateID);
						} catch (Exception e) {
						}
						templateDetailSql.addTemplateInfo(detailInfo,
								templateID);
					}
					generateTemplate();
					finishedLoad(TAG);
				}
			 
				generateTemplate();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(TemplateDetailInfo result,
					int iErrorCode) throws Exception {
				loadingFailed(TAG, iErrorCode);
				// finish();
				Log.e("TAG", "从服务器获取内容异常");
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				getDataFromSql();
			}
		}.execute();
	}
	
	private class TemplateItem implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = -8517011347819302002L;
		@SuppressWarnings("unused")
		@SerializedName("item-id")
		public int id;
	}

	/**合计统计EditText*/
	private EditText totalEdit;
	/**是否包含统计*/
	private boolean istotal = false;
	 
	private void generateTemplate() {
		if (detailInfo == null) {
			Toast.makeText(this, "获取数据失败！请稍后再试！", Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		try {
		 
			for (final TemplateItemInfo itemInfo : detailInfo.getItems()) {
				//
//				Log.e("模板", "position: = "+itemInfo.getPosition()+" , type: = " + itemInfo.getType() + " , id: = " + itemInfo.getId() + " , name: = " + itemInfo.getName() + " , templateID: = " + templateID);
				if(itemInfo.getType() == ITEM_TYPE_TOTAL){
					istotal = true;
					LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.editview, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					totalEdit = (EditText) layout.getChildAt(1);
					if(!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())){
						totalEdit.setHint(itemInfo.getBook_notice());
					}
					totalEdit.setEnabled(false);
					items.put(itemInfo.getId(), ITEM_TYPE_TOTAL);
					rootLayout.addView(layout);
				}else if (itemInfo.getType() == ITEM_TYPE_TEXTVIEW) {
					final TextView textView = (TextView) LayoutInflater.from(this)
							.inflate(R.layout.textview, null);
					textView.setId(itemInfo.getId());
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(textView, 100, 0);
							}
						});
					}
					items.put(textView.hashCode(), ITEM_TYPE_TEXTVIEW);
					textView.setText(itemInfo.getName());
					rootLayout.addView(textView);
				} else if (itemInfo.getType() == ITEM_TYPE_EDITVIEW) {
					LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.editview, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}

					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					EditText editText = (EditText) layout.getChildAt(1);
					if(!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())){
						editText.setHint(itemInfo.getBook_notice());
					}
					editText.setId(itemInfo.getId());
					
					items.put(itemInfo.getId(), ITEM_TYPE_EDITVIEW);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_TEXTAREA) {
					LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.textareaview, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					EditText editText = (EditText) layout.getChildAt(1);
					if(!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())){
						editText.setHint(itemInfo.getBook_notice());
					}
					editText.setId(itemInfo.getId());
					items.put(itemInfo.getId(), ITEM_TYPE_TEXTAREA);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_DATE) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.date, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								// popupWindow.showAsDropDown(layout.getChildAt(0));
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					final EditText showDate = (EditText) layout.getChildAt(1);
					showDate.setId(itemInfo.getId());
					Button pickDate = (Button) layout.getChildAt(2);
					pickDate.setId(itemInfo.getId());
					initializeViews(pickDate, showDate);

					final Calendar c = Calendar.getInstance();

					mYear = c.get(Calendar.YEAR);

					mMonth = c.get(Calendar.MONTH);

					mDay = c.get(Calendar.DAY_OF_MONTH);

					mHour = c.get(Calendar.HOUR_OF_DAY);

					mMinute = c.get(Calendar.MINUTE);

					setDateTime(showDate);
					items.put(itemInfo.getId(), ITEM_TYPE_DATE);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_TIME) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.time, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								// popupWindow.showAsDropDown(layout.getChildAt(0));
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					Button pickTime = null;
					final EditText showTime = (EditText) layout.getChildAt(1);
					showTime.setId(itemInfo.getId());
					pickTime = (Button) layout.getChildAt(2);
					pickTime.setId(itemInfo.getId());

					initializeViewsTime(pickTime, showTime);

					final Calendar c = Calendar.getInstance();

					mYear = c.get(Calendar.YEAR);

					mMonth = c.get(Calendar.MONTH);

					mDay = c.get(Calendar.DAY_OF_MONTH);

					mHour = c.get(Calendar.HOUR_OF_DAY);

					mMinute = c.get(Calendar.MINUTE);

					setTimeOfDay(showTime);
					items.put(itemInfo.getId(), ITEM_TYPE_TIME);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_SELECT) {
					final int itemId = itemInfo.getId();
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.select, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								// popupWindow.showAsDropDown(layout.getChildAt(0));
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					final Spinner spinner = (Spinner) layout.getChildAt(1);
					spinner.setId(itemInfo.getId());
					String[] show = {};

					if (selectInfoSql.getCount(itemId) > 0) {
						li = selectInfoSql.getTemplateInfo(itemId);
					} else {
						if ((BizApp.getInstance().isNetworkAvailable() || BizApp
								.getInstance().isWiFiActive())
								&& BizApp.getInstance().keeping) {
							try {
								TemplateItem id = new TemplateItem();
								id.id = itemInfo.getId();
								try {
									li = ServiceHelper.getInstance().postData(
											ServiceHost.templateitemoption(),
											new Gson().toJson(id),
											TempleteSelectListInfo.class);
								} catch (Exception e) {
									if (PrefsUtils.getURL().equals(
											StringUtil.URL1)) {
										PrefsUtils.setURL(StringUtil.URL2);
									} else if (PrefsUtils.getURL().equals(
											StringUtil.URL2)) {
										PrefsUtils.setURL(StringUtil.URL1);
									}
									try {
										li = ServiceHelper
												.getInstance()
												.postData(
														ServiceHost
																.templateitemoption(),
														new Gson().toJson(id),
														TempleteSelectListInfo.class);
									} catch (Exception ex) {
										if (PrefsUtils.getURL().equals(
												StringUtil.URL1)) {
											PrefsUtils.setURL(StringUtil.URL2);
										} else if (PrefsUtils.getURL().equals(
												StringUtil.URL2)) {
											PrefsUtils.setURL(StringUtil.URL1);
										}
									}
								}
								if (li != null) {
									try {
										selectInfoSql.deleteAttribute(itemId);
									} catch (Exception e) {
									}
									selectInfoSql.addTemplateInfo(li, itemId);
								}
							} catch (Exception e) {
								Toast.makeText(context,
										"获取" + itemInfo.getName() + "数据异常",
										Toast.LENGTH_SHORT).show();
							}
						}
					}

					if (li != null && li.getTemplates() != null
							&& li.getTemplates().size() > 0) {
						Message msg = handler.obtainMessage(itemInfo.getId(), 1, 1, li);
						handler.sendMessage(msg);
					 
						show = new String[li.getTemplates().size()];
						for (int i = 0; i < li.getTemplates().size(); i++) {
							show[i] = li.getTemplates().get(i).getName();
						}
						ArrayAdapter<String> adapter = new ArrayAdapter<String>(
								ReportActivity.this,
								android.R.layout.simple_spinner_item, show);

						adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
						spinner.setAdapter(adapter);
						 
						spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

							public void onItemSelected(AdapterView<?> parent,
									View view,

									int position, long id) {

								selects.put(itemInfo.getId(), spinner
										.getSelectedItem().toString().trim());
							
//								Log.e("选择后", "select: = " + spinner.getSelectedItem().toString().trim() + " , id: = " + itemInfo.getId());
								//
								if(StringUtil.isNum(spinner.getSelectedItem().toString().trim()) && istotal){
									if(totalMap.containsKey(itemId)){
										totalMap.remove(itemId);
									}
									totalMap.put(itemId, Integer.parseInt(spinner.getSelectedItem().toString().trim()));
									 
									Message msg = new Message();
									msg.what = 0x003;
									totalhandler.sendMessage(msg);
								}
								
							}

							 
							public void onNothingSelected(AdapterView<?> arg0) {

							}
						});

						 
						items.put(itemInfo.getId(), ITEM_TYPE_SELECT);
						rootLayout.addView(layout);
					}

				} else if (itemInfo.getType() == ITEM_TYPE_CHECKBOX) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.checkbox, null);
					CheckBox chb = (CheckBox) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						chb.setText(itemInfo.getName() + "(*)");
					} else {
						chb.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						chb.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					chb.setId(itemInfo.getId());
					items.put(itemInfo.getId(), ITEM_TYPE_CHECKBOX);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_POI) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.edit_autotextview, null);
					TextView textView1 = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView1.setText(itemInfo.getName() + "(*)");
					} else {
						textView1.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView1.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					textView = (MyAutoCompleteTextView) layout.getChildAt(1);

					int count = cssql.getCount();
					if ((BizApp.getInstance().isNetworkAvailable() || BizApp
							.getInstance().isWiFiActive())
							&& BizApp.getInstance().keeping) {
						CommonBody body = new CommonBody();
						body.setCommand(1);
						body.setImsi(BizApp.getInstance().getIMSI());
						body.setVersion(getString(R.string.app_version));
						LocationPageinfo pageInfo = new LocationPageinfo();
						pageInfo.begin = 1;
						pageInfo.end = 100;
						pageInfo.lon = BizApp.getInstance().getLon();
						pageInfo.lat = BizApp.getInstance().getLat();
						i = null;
						try {
							i = ServiceHelper.getInstance().postData(
									ServiceHost.getClientsURL(),
									gson.toJson(body), gson.toJson(pageInfo),
									ClientListInfo.class);

						} catch (Exception e) {
							if(PrefsUtils.getURL().equals(StringUtil.URL1)){
								PrefsUtils.setURL(StringUtil.URL2);
							}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
								PrefsUtils.setURL(StringUtil.URL1);
							}
							try{
							i = ServiceHelper.getInstance().postData(
									ServiceHost.getClientsURL(),
									gson.toJson(body), gson.toJson(pageInfo),
									ClientListInfo.class);
							}catch (Exception ex) {
								if(PrefsUtils.getURL().equals(StringUtil.URL1)){
									PrefsUtils.setURL(StringUtil.URL2);
								}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
									PrefsUtils.setURL(StringUtil.URL1);
								}
							}
						}

						if (i != null && i.getClients() != null) {
							int countInService = i.getClients().size();
							if (count != countInService) {
								cssql.delete();
								for (int j = 0; j < i.getClients().size(); j++) {
									cssql.addClientInfo(i.getClients().get(j));
								}
							}
						}

					} else {

						if (cssql.getCount() > 0) {
							i = cssql.getClientInfo(0, count, null);
						} else {
							// Log.e("客户选择", "本地客户为null");
						}
					}
					if (i != null && i.getClients() != null
							&& i.getClients().size() > 0) {
						mOriginalValues.clear();
						mOriginalValues = (ArrayList<ClientInfo>) i
								.getClients();
					}
					adapter = new AutoCompleteAdapter(ReportActivity.this,
							mOriginalValues, 100);
					textView.setAdapter(adapter);
					textView.setOnFocusChangeListener(new OnFocusChangeListener() {
						public void onFocusChange(View v, boolean hasFocus) {
							EditText _v = (EditText) v;
							if (!hasFocus) {// 失去焦点
								// _v.setHint(_v.getTag().toString());
							} else {
								_v.setText("");
								poi_id = -1;
							}
						}
					});

					textView.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							poi_id = ((ClientInfo) adapter
									.getCustomer(position)).getId();
						}
					});

					Button but = (Button) layout.getChildAt(2);
					but.setOnClickListener(new OnClickListener() {
						//
						@Override
						public void onClick(View v) {
							Bundle bundle = new Bundle();
							IntentUtil.redirectToNext(ReportActivity.this,
									ClientSelectListActivity.class, bundle);
						}
					});
					items.put(itemInfo.getId(), ITEM_TYPE_POI);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_PRODUCT) {
					LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.edit_pro_autotextview, null);
					TextView textView1 = (TextView) layout.getChildAt(0);
					
					if (itemInfo.getRequired_flag() == 1) {
						textView1.setText(itemInfo.getName() + "(*)");
					} else {
						textView1.setText(itemInfo.getName());
					}
					
					productEdit = (ProMyAutoCompleteTextView) layout
							.getChildAt(1);
					if(!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())){
						productEdit.setHint(itemInfo.getBook_notice());
					}else{
						productEdit.setHint("请选择或扫描产品");
					}
					if ((BizApp.getInstance().isNetworkAvailable() || BizApp
							.getInstance().isWiFiActive())
							&& BizApp.getInstance().keeping) {

						PageInfo pageInfo = new PageInfo();
						pageInfo.begin = 1;
						pageInfo.end = 100;
						try {
							p = ServiceHelper.getInstance().postData(
									ServiceHost.product(),
									new Gson().toJson(pageInfo),
									ProductListInfo.class);
						} catch (Exception e) {
							if(PrefsUtils.getURL().equals(StringUtil.URL1)){
								PrefsUtils.setURL(StringUtil.URL2);
							}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
								PrefsUtils.setURL(StringUtil.URL1);
							}
							try{
								p = ServiceHelper.getInstance().postData(
										ServiceHost.product(),
										new Gson().toJson(pageInfo),
										ProductListInfo.class);
							}catch (Exception ex) {
								if(PrefsUtils.getURL().equals(StringUtil.URL1)){
									PrefsUtils.setURL(StringUtil.URL2);
								}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
									PrefsUtils.setURL(StringUtil.URL1);
								}
							}
						}
						if (p != null && p.getProducts() != null) {

							if (p.getProducts().size() != productSql.getCount()) {
								productSql.deleteProItem();

								for (ProductInfo info : p.getProducts()) {

									if (info.getGid() != null && info.getGid().length() > 0) {
										String[] gids = info.getGid()
												.split(",");
										for (int i = 0; i < gids.length; i++) {
											productSql.addProductInfo(info,
													Integer.valueOf(gids[i]));
										}
									}

								}

							}
						}
					} else {
						p = productSql.getProduct();
					}
					if (p != null && p.getProducts() != null
							&& p.getProducts().size() > 0) {
						pro_mOriginalValues.clear();
						for (ProductInfo c : p.getProducts()) {
							pro_mOriginalValues.add(c.getName());
						}
					}
					pro_adapter = new ProAutoCompleteAdapter(
							ReportActivity.this, pro_mOriginalValues, 20);
					productEdit.setAdapter(pro_adapter);
					productEdit.setOnItemClickListener(new OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							if(proMap.containsKey(itemInfo.getId())){
								proMap.remove(itemInfo.getId());
							}
							proMap.put(itemInfo.getId(), p.getProducts().get(position).getProduct_id());
 
						}
					});
					productEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
						public void onFocusChange(View v, boolean hasFocus) {
							EditText _v = (EditText) v;
							if (!hasFocus) {// 失去焦点
								// _v.setHint(_v.getTag().toString());
							} else {
								if(proMap != null){
									proMap.clear();
								}
								_v.setText("");
							}
						}
					});
					productEdit.addTextChangedListener(new TextWatcher() {
						public void beforeTextChanged(CharSequence s,
								int start, int count, int after) {

						}

						public void onTextChanged(CharSequence s, int start,
								int before, int count) {

						}

						public void afterTextChanged(Editable s) {
//							pro_id = -1;
							if(proMap.containsKey(itemInfo.getId())){
								proMap.remove(itemInfo.getId());
							}
						}
					});
					Button button = (Button) layout.getChildAt(2);
					button.setOnClickListener(new OnClickListener() {
						
						@Override
						public void onClick(View v) {
							productEdit.setText("");
							if(proMap.containsKey(itemInfo.getId())){
								proMap.remove(itemInfo.getId());
							}
							product_edit_item_id = itemInfo.getId();
							
							Intent intent = new Intent();
							intent.putExtra("isProduct", true);
							intent.setClass(context, CaptureActivity.class);
							startActivityForResult(intent, 323);
						}
					});
					items.put(itemInfo.getId(), ITEM_TYPE_PRODUCT);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_IMAGEVIEW) {
					final LinearLayout layout = (LinearLayout) LayoutInflater
							.from(this).inflate(R.layout.imagebutton, null);
					ImageView img = (ImageView) layout.getChildAt(0);
					img.setImageResource(R.drawable.slr_camera);
					Button btn = (Button) layout.getChildAt(1);
					btn.setId(itemInfo.getId());
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						img.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					btn.setBackgroundResource(R.drawable.btn_gray_selector);
					if (itemInfo.getRequired_flag() == 1) {
						btn.setText(itemInfo.getName() + "(*)");
					} else {
						btn.setText(itemInfo.getName());
					}
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					btn.setTextColor(getResources().getColor(R.color.black));
					
					btn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							bundle = new Bundle();
							bundle.putInt(PersistentKeyUtil.TEMPLATE_ITEM_ID,
									v.getId());

							chooseimage = (ImageView) layout.getChildAt(0);
							String status = Environment
									.getExternalStorageState();
							if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
								try{
									BizApp.getInstance().showMemory();
								}catch (Exception e) {
								}
							      PrefsUtils.setHaseRote(null);
							      if (!PHOTO_DIR.exists()) {
										PHOTO_DIR.mkdirs();
									}
									String FileName = System.currentTimeMillis() + ".jpg";
									mCurrentPhotoFile = new File(PHOTO_DIR, FileName);
									PrefsUtils.setImageFile(mCurrentPhotoFile.getAbsolutePath());
									Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
									intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCurrentPhotoFile));
									startActivityForResult(intent, 321);
							} else {
								Toast.makeText(ReportActivity.this, "没有SD卡",
										Toast.LENGTH_LONG).show();
							}
						}
					});
					items.put(itemInfo.getId(), ITEM_TYPE_IMAGEVIEW);
					rootLayout.addView(layout);
					hasImage = true;
				} else if (itemInfo.getType() == ITEM_TYPE_CODE) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.imagebutton, null);
					ImageView img = (ImageView) layout.getChildAt(0);
					img.setBackgroundResource(R.drawable.icode);
					Button btn = (Button) layout.getChildAt(1);
					btn.setId(itemInfo.getId());
					// imgId = itemInfo.getId();
					btn.setBackgroundResource(R.drawable.btn_gray_selector);
					if (itemInfo.getRequired_flag() == 1) {
						btn.setText(itemInfo.getName() + "(*)");
					} else {
						btn.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						img.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								// popupWindow.showAsDropDown(layout.getChildAt(0));
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					btn.setTextColor(getResources().getColor(R.color.black));
					btn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							sf = true;
							IntentUtil.redirectToNext(ReportActivity.this,
									CaptureActivity.class);
						}
					});
					sId = itemInfo.getId();
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					items.put(itemInfo.getId(), ITEM_TYPE_CODE);
					rootLayout.addView(layout);
					hasImage = true;
				} else if (itemInfo.getType() == ITEM_TYPE_NUMBERIC) {
					LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.editview, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					EditText editText = (EditText) layout.getChildAt(1);
					if(!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())){
						editText.setHint(itemInfo.getBook_notice());
					}
					editText.setId(itemInfo.getId());
					editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
					editText.setKeyListener(DigitsKeyListener.getInstance(true,
							true));
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					items.put(itemInfo.getId(), ITEM_TYPE_NUMBERIC);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_RECORD) {
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.buttonview, null);
					TextView textView = (TextView) layout.getChildAt(0);
					if (itemInfo.getRequired_flag() == 1) {
						textView.setText(itemInfo.getName() + "(*)");
					} else {
						textView.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						textView.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					final Button btn = (Button) layout.getChildAt(1);
					btn.setId(itemInfo.getId());
					final TextView textView1 = (TextView) layout.getChildAt(2);
					btn.setBackgroundResource(R.drawable.media_record);
					btn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							if (!isStart) {
								initRecorder();
								startRecorder();
								btn.setBackgroundResource(R.drawable.record_stop);
								textView1.setText("正在录音...");
							} else {
								stopRecorder();
								btn.setBackgroundResource(R.drawable.media_record);
								textView1.setText("录音时长：" + time / 1000 + "秒");
							}

						}
					});
					flagItems
							.put(itemInfo.getId(), itemInfo.getRequired_flag());
					rId = itemInfo.getId();
					items.put(itemInfo.getId(), ITEM_TYPE_RECORD);
					rootLayout.addView(layout);
				} else if (itemInfo.getType() == ITEM_TYPE_VIDEO) {
					// 录像 type
					final LinearLayout layout = (LinearLayout) LayoutInflater.from(
							this).inflate(R.layout.imagebutton, null);
					ImageView img = (ImageView) layout.getChildAt(0);
					img.setBackgroundResource(R.drawable.movie_studio);
					Button btn = (Button) layout.getChildAt(1);
					btn.setId(itemInfo.getId());
					btn.setBackgroundResource(R.drawable.btn_gray_selector);
					if (itemInfo.getRequired_flag() == 1) {
						btn.setText(itemInfo.getName() + "(*)");
					} else {
						btn.setText(itemInfo.getName());
					}
					if (!StringUtil.isEmptyOrNull(itemInfo.getBook_notice())) {
						img.setOnClickListener(new OnClickListener() {

							@Override
							public void onClick(View v) {
								book_notice_text.setText(itemInfo.getBook_notice());
								popupWindow.showAsDropDown(layout.getChildAt(0), 100, 0);
							}
						});
					}
					btn.setTextColor(getResources().getColor(R.color.black));
					btn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							Intent intent = new Intent(
									MediaStore.ACTION_VIDEO_CAPTURE);
							intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
							intent.putExtra(MediaStore.EXTRA_FULL_SCREEN, 1);
							startActivityForResult(intent, ITEM_TYPE_VIDEO);
						}
					});
					vId = itemInfo.getId();
					items.put(itemInfo.getId(), ITEM_TYPE_VIDEO);
					rootLayout.addView(layout);

				}

			}
		} catch (Exception e) {
			Toast.makeText(this, "模板加载异常", Toast.LENGTH_SHORT).show();
			//e.printStackTrace();
		}
		LinearLayout layout = (LinearLayout) LayoutInflater.from(this).inflate(
				R.layout.button, null);
		Button btn = (Button) layout.getChildAt(0);
		btn.setText("上传汇报");
		Button btn1 = (Button) layout.getChildAt(1);
		btn1.setText("保存本地");
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				isUpBtn = true;
				flag11 = false;
				if ((BizApp.getInstance().isWiFiActive() || BizApp
						.getInstance().isNetworkAvailable())
						&& BizApp.getInstance().keeping) {
					if (location_flg != 0) {
						checkLocation();
//						Log.e("TAG", "获取位置");
					} else {
//						Log.e("TAG", "获取上传内容");
						getContents();
					}
				} else {
					getContents();
				}

			}
		});
		btn1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				isUpBtn = false;
				flag11 = true;
				bcount++;
				if (BizApp.getInstance().isNetworkAvailable()
						|| BizApp.getInstance().isWiFiActive()) {
					if (location_flg != 0) {
						checkLocation();
					} else {
						getContents();
					}
				} else {
					getContents();
				}

			}
		});
		rootLayout.addView(layout);
		LinearLayout layout1 = (LinearLayout) LayoutInflater.from(this)
				.inflate(R.layout.view, null);
		rootLayout.addView(layout1);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			String string = String.valueOf(msg.what);
			TempleteSelectListInfo li = (TempleteSelectListInfo) msg.obj;
			Mali.put(Integer.parseInt(string), li);

		};
	};
	
	private Handler totalhandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == 0x003) {
				int total = 0;
				for (Iterator<Map.Entry<Integer, Integer>> it = totalMap
						.entrySet().iterator(); it.hasNext();) {
					Map.Entry<Integer, Integer> entry = it.next();
					entry.getKey();
					total = total + entry.getValue();
				}
				if(totalEdit != null){
					totalEdit.setText(total + "");
				}
			}
		};
	};

	/**
	 * 准备录音
	 */
	private void initRecorder() {
		isSDCardExit = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED);
		if (isSDCardExit) {
			SDPathDir = Environment.getExternalStorageDirectory();
		}

		recorder = new MediaRecorder();
		/* 设置音频源 */
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		/* 设置输出格式 */
		recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
		/* 设置音频编码器 */
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);

		try {
			/* 创建一个临时文件，用来存放录音 */
			tempFile = File.createTempFile("/tempFile", ".amr", SDPathDir);
			// Log.e("file", tempFile.getAbsolutePath());
			/* 设置录音文件 */
			recorder.setOutputFile(tempFile.getAbsolutePath());
		} catch (IOException e) {

			//e.printStackTrace();
		}

	}

	/**
	 * 开始录音
	 */
	private void startRecorder() {
		try {
			if (!isSDCardExit) {
				Toast.makeText(this, "请插入SD卡", Toast.LENGTH_LONG).show();
				return;
			}
			recorder.prepare();
			recorder.start();
			isStart = true;
			time = Calendar.getInstance().getTimeInMillis();
		} catch (IllegalStateException e) {
		} catch (IOException e) {
		}
	}

	/**
	 * 停止录音
	 */
	private void stopRecorder() {
		if (recorder != null) {
			recorder.stop();
			recorder.release();// 释放资源
			recorder = null;
			PrefsUtils.setReportRecordPath(tempFile.getAbsolutePath());
			isStart = false;
			time = Calendar.getInstance().getTimeInMillis() - time;
		}
	}

	private void checkLocation() {

//		 Log.e("当前地理位置", BizApp.getInstance().getLat() + ",,"
//		 + BizApp.getInstance().getLon());
		if (BizApp.getInstance().isNetworkAvailable()
				|| BizApp.getInstance().isWiFiActive()) {
			if (BizApp.getInstance().getCurrentLocation() == null
					|| BizApp.getInstance().getLat() < 0.0001
					|| BizApp.getInstance().getLon() < 0.0001
					|| System.currentTimeMillis() > (BizApp.getInstance()
							.getLocTime() + 70000)) {

				final DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (DialogInterface.BUTTON_POSITIVE == which) {
							NLOC = false;
							getContents();
							NLOC = true;

						} else {
							dialog.dismiss();
						}
					}
				};

				if (BizApp.getInstance().isWiFiActive()
						|| BizApp.getInstance().isNetworkAvailable()) {
					BizApp.getInstance().getmLocationClient().start();
					showLoading("正在获取地理位置");
					registerLoadStatus(TAG);
					new AsyncTask<Void, Void, Void>() {
						protected Void doInBackground(Void... params) {

							try {
								Thread.sleep(7000);
							} catch (Exception e) {
								//e.printStackTrace();
							}
							// data.remove(0);
							return null;
						}

						@Override
						protected void onPostExecute(Void result) {

							finishedLoad(TAG);

							if (BizApp.getInstance().getCurrentLocation() == null
									|| BizApp.getInstance().getLat() < 0.0001
									|| BizApp.getInstance().getLon() < 0.0001
									|| System.currentTimeMillis() > (BizApp
											.getInstance().getLocTime() + 70000)) {
								// Log.e("===", "cellId： = "
								// + LocationUtils.getInstance()
								// .getLocationMsg().split(",")[3]);

								if (LocationUtils.getInstance()
										.getLocationMsg().split(",")[3]
										.equals("0")) {
									DialogUtil.getAlertDialog(
											ReportActivity.this,
											getString(R.string.alert_title),
											"无法获取位置信息，是否继续?",
											getString(R.string.yes), listener2,
											getString(R.string.no), null)
											.show();
								} else {
									hideLoading();
									getContents();
								}
							} else {
//								 Log.e("获取地理位置异常",
//								 BizApp.getInstance().getLat()
//								 + ",," + BizApp.getInstance().getLon());
								hideLoading();
								getContents();

								// showLoading("正在上传数据");
							}
						}

					}.execute();
				} else {
					if (BizApp.getInstance().getCurrentLocation() == null
							|| BizApp.getInstance().getLat() < 0.0001
							|| BizApp.getInstance().getLon() < 0.0001
							|| System.currentTimeMillis() > (BizApp
									.getInstance().getLocTime() + 70000)) {
//						 Log.e("获取到cellid", "cellId： = "
//						 + LocationUtils.getInstance().getLocationMsg()
//						 .split(",")[3]);

						if (LocationUtils.getInstance().getLocationMsg()
								.split(",")[3].equals("0")) {
							DialogUtil.getAlertDialog(ReportActivity.this,
									getString(R.string.alert_title),
									"无法获取位置信息，是否继续?", getString(R.string.yes),
									listener2, getString(R.string.no), null)
									.show();
						}
					}
				}

			} else {
				getContents();

			}
		} else {
			getContents();
		}
	}

	private void getContents() {
		uploadInfo = new UploadInfo();
		uploadInfo.items = new ArrayList<UploadItemInfo>();
		UploadItemInfo itemInfo = null;
		String str = null;
		for (Iterator<Map.Entry<Integer, Integer>> it = items.entrySet()
				.iterator(); it.hasNext();) {
			Map.Entry<Integer, Integer> entry = it.next();
			entry.getKey();
			str = null;
			if(entry.getValue() == ITEM_TYPE_TOTAL){
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_TOTAL;
				String value = "";
				if(totalEdit != null && !StringUtil.isEmptyOrNull(totalEdit.getText().toString().trim())){
					value = totalEdit.getText().toString().trim();
				}
				itemInfo.value = value;
				uploadInfo.items.add(itemInfo);
			}else if (entry.getValue() == ITEM_TYPE_CHECKBOX) {
				CheckBox chb = (CheckBox) rootLayout.findViewById(entry
						.getKey());
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_CHECKBOX;
				itemInfo.value = chb.isChecked() ? "1" : "0";
				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_EDITVIEW) {
				EditText editText = (EditText) rootLayout.findViewById(entry
						.getKey());
				str = editText.getText().toString().trim();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "文本填写不完整", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_EDITVIEW;
				itemInfo.value = str;
				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_POI) {
				if (poi_id == -1) {
					Toast.makeText(this, "客户输入错误，请重新输入后选择", Toast.LENGTH_SHORT)
							.show();
					if (bcount >= 1) {
						bcount = bcount - 1;
					}
					return;
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_POI;
				if (poi_id == 0) {
					itemInfo.value = "";
				} else {
					itemInfo.value = String.valueOf(poi_id);
				}

				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_PRODUCT) {
				int pro_id = -1;
				if(proMap != null && proMap.size() > 0 && proMap.containsKey(entry.getKey())){
					pro_id = proMap.get(entry.getKey());
				}
				if (pro_id == -1) {
					Toast.makeText(this, "产品输入错误，请重新输入后选择", Toast.LENGTH_SHORT)
							.show();
					if (bcount >= 1) {
						bcount = bcount - 1;
					}
					return;
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_PRODUCT;
				if (pro_id == 0) {
					itemInfo.value = "";
				} else {
					itemInfo.value = String.valueOf(pro_id);
				}
				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_TEXTAREA) {
				EditText editText = (EditText) rootLayout.findViewById(entry
						.getKey());
				str = editText.getText().toString().trim();
				if (flagItems.get(entry.getKey()) == 1) {
				if (StringUtil.isEmptyOrNull(str)) {
					Toast.makeText(this, "长文本填写不完整", Toast.LENGTH_SHORT).show();
					return;
				}
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_TEXTAREA;
				itemInfo.value = str;
				uploadInfo.items.add(itemInfo);

			} else if (entry.getValue() == ITEM_TYPE_DATE) {
				EditText editText = (EditText) rootLayout.findViewById(entry
						.getKey());
				str = editText.getText().toString().trim();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "日期填写不完整", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_DATE;
				itemInfo.value = StringUtil.DateTomill(str).toString();
				uploadInfo.items.add(itemInfo);

			} else if (entry.getValue() == ITEM_TYPE_TIME) {
				EditText editText = (EditText) rootLayout.findViewById(entry
						.getKey());
				str = editText.getText().toString().trim();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "时间填写不完整", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_TIME;
				itemInfo.value = str;
				uploadInfo.items.add(itemInfo);

			} else if (entry.getValue() == ITEM_TYPE_SELECT) {

				String result = selects.get(entry.getKey());

				TempleteSelectListInfo aa = Mali.get(entry.getKey());

				for (int i = 0; i < aa.getTemplates().size(); i++) {
					if (result != null
							&& result
									.equals(aa.getTemplates().get(i).getName().trim())) {
						str = String.valueOf(aa.getTemplates().get(i)
								.getOption_id());
					}
				}

				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_SELECT;
				itemInfo.value = str;

				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_CODE) {
				str = PrefsUtils.getReportCodeValue();
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_CODE;
				if (BarcodeFormat.EAN_13.equals(PrefsUtils.getReportCodeType())) {
					itemInfo.ext_type = 101;
				}
				if (BarcodeFormat.EAN_8.equals(PrefsUtils.getReportCodeType())) {
					itemInfo.ext_type = 102;
				}
				if (BarcodeFormat.CODE_39
						.equals(PrefsUtils.getReportCodeType())) {
					itemInfo.ext_type = 103;
				}
				if (BarcodeFormat.CODE_128.equals(PrefsUtils
						.getReportCodeType())) {
					itemInfo.ext_type = 105;
				}
				if (BarcodeFormat.QR_CODE
						.equals(PrefsUtils.getReportCodeType())) {
					itemInfo.ext_type = 121;
				}
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "扫描码不能为空!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
				itemInfo.value = str;
				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_NUMBERIC) {
				EditText editText = (EditText) rootLayout.findViewById(entry
						.getKey());
				str = editText.getText().toString().trim();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "内容填写不完整!", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}
				itemInfo = new UploadItemInfo();
				itemInfo.id = entry.getKey();
				itemInfo.type = ITEM_TYPE_NUMBERIC;
				itemInfo.value = str;
				uploadInfo.items.add(itemInfo);
			} else if (entry.getValue() == ITEM_TYPE_IMAGEVIEW) {
				str = PrefsUtils.getReportImagePath();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "请拍摄照片！", Toast.LENGTH_SHORT)
								.show();
						return;
					}
				}

			} else if (entry.getValue() == ITEM_TYPE_RECORD) {
				str = PrefsUtils.getReportRecordPath();
				if (flagItems.get(entry.getKey()) == 1) {
					if (StringUtil.isEmptyOrNull(str)) {
						Toast.makeText(this, "请录音！", Toast.LENGTH_SHORT).show();
						return;
					}
				}
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		uploadInfo.date = sdf.format(Calendar.getInstance().getTime());
		uploadInfo.id = templateID;
		uploadInfo.locationMsg = LocationUtils.getInstance().getLocationMsg();
		uploadInfo.lat = BizApp.getInstance().getLat();
		uploadInfo.lon = BizApp.getInstance().getLon();
		if (NLOC) {
			if (location_flg == 0) {
				// uploadInfo.lat = 0.0;
				// uploadInfo.lon = 0.0;
				// // uploadInfo.locationMsg = "0,0,0,0,0";
			}
		}
		uploadInfo.address = BizApp.getInstance().getAddress();
		if (reportType == 0) {
			uploadInfo.type = 1;
		} else {
			uploadInfo.type = 3;
		}

		if (reportType == 0) {
		} else {
			uploadInfo.reportId = taskId;
		}
		if (detailInfo != null && detailInfo.getItems() != null
				&& uploadInfo != null && uploadInfo.items != null) {
			for (TemplateItemInfo tinfo : detailInfo.getItems()) {
				for (UploadItemInfo i : uploadInfo.items) {
					if (tinfo.getId() == i.id) {
						if (tinfo.getRequired_flag() == 1
								&& (i.value == null || "".equals(i.value))) {
							if (bcount >= 1) {
								bcount = bcount - 1;
							}
							Toast.makeText(this, tinfo.getName() + "不可为空",
									Toast.LENGTH_SHORT).show();
							return;
						}
					}
				}
				if (tinfo.getType() == 4) {
					if (tinfo.getRequired_flag() == 1
							&& StringUtil.isEmptyOrNull(PrefsUtils
									.getReportImagePath())) {
						if (bcount >= 1) {
							bcount = bcount - 1;
						}
						Toast.makeText(this, tinfo.getName() + "不可为空",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
				if (tinfo.getType() == 7) {
					if (tinfo.getRequired_flag() == 1
							&& StringUtil.isEmptyOrNull(PrefsUtils
									.getReportRecordPath())) {
						if (bcount >= 1) {
							bcount = bcount - 1;
						}
						Toast.makeText(this, tinfo.getName() + "不可为空",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
				if (tinfo.getType() == 8) {
					if (bcount >= 1) {
						bcount = bcount - 1;
					}
					if (tinfo.getRequired_flag() == 1 && capre == null) {
						Toast.makeText(this, tinfo.getName() + "不可为空",
								Toast.LENGTH_SHORT).show();
						return;
					}
				}
			}
		}
		if (!flag11) {

			 
			upload();
		} else {
			save();
		}
	}

	private void save() {
		// Log.e("aaa", gson.toJson(uploadInfo));
		ContextInfo cinfo = new ContextInfo();
		cinfo.setContext(gson.toJson(uploadInfo));
		Log.e("TAG", "保存的内容： = " + gson.toJson(uploadInfo));
		if (taskId == 0) {
			cinfo.setType(0);
		} else {
			cinfo.setType(1);
		}

		cinfo.setName(templateName);
		cinfo.setDate(StringUtil.getCurrentTime());
		if (!StringUtil.isEmptyOrNull(PrefsUtils.getReportImagePath())) {
			cinfo.setImgpath(PrefsUtils.getReportImagePath());
		}
		if (!StringUtil.isEmptyOrNull(PrefsUtils.getReportRecordPath())) {
			cinfo.setRecpath(rId + "," + PrefsUtils.getReportRecordPath());
		}
		if (capre != null) {
			cinfo.setVediopath(vId + "," + capre);
		}
		csql.addContextInfo(cinfo);

//		ReportHistoryInfo history = new ReportHistoryInfo();
//		if (reportType == 1) {
//			String time = taskTime;
//			String qti = "";
//			if (time != null && time.length() > 10) {
//				qti = time.substring(11, time.length());
//			}
//			if ("00:00:00.0".equals(qti)) {
//				time = StringUtil.getFormTaskTime(taskTime);
//			} else {
//				time = StringUtil.getTaskTime(taskTime);
//			}
//			history.name = time + " " + taskName + "(" + templateName + ")";
//
//		} else {
//			history.name = templateName;
//		}
//		history.date = StringUtil.getReportTime();
//		history.type = (reportType == 1 ? 3
//				: PersistentKeyUtil.REPORT_TYPE_DIRECTLY);
//
//		BizApp.getInstance().getSqlHelper().addHistory(history);

		if (fromTask) {
			temSql.deleteAttribute(templateID, taskId);
		}

		Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show();

		if (reportType == 1) {

			tnsql.addAttribute(taskId, templateID);
		}

		detailInfo = null;
		// PrefsUtils.setReportImagePath("");
		// pd.dismiss();
		if (taskId != 0) {
			this.finish();
		} else {
			TextView tv = (TextView) findViewById(R.id.txt111);
			if (isUpBtn) {
				if (BizApp.getInstance().isNetworkAvailable()
						|| BizApp.getInstance().isWiFiActive()) {
					tv.setText("本模板第" + bcount + "次保存，请继续新的操作或返回");
				}
			} else {
				tv.setText("本模板第" + bcount + "次保存，请继续新的操作或返回");
			}
		}
		return;
	}

	private void upload() {
		try {

			showLoading("正在上传数据");

			if (!StringUtil.isEmptyOrNull(PrefsUtils.getReportRecordPath())) {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buf = new byte[8 * 1024];
				try {
					CommonBody body = new CommonBody();
					body.setCommand(2);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					body.setFile("amr");
					body.setBegin_index(0);
					String reqBody = gson.toJson(body);
					reqBody = reqBody + "\r\n\r\n";
					bos.write(reqBody.getBytes("ISO-8859-1"));
					FileInputStream fis = new FileInputStream(
							PrefsUtils.getReportRecordPath());// "/mnt/sdcard/atsmart/example.jpg");//

					for (int readNum; (readNum = fis.read(buf)) != -1;) {
						if (bos.toByteArray().length < 100000) {
							bos.write(buf, 0, readNum);
							re_length += buf.length;
						} else {
							break;
						}
					}
					bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
					fis.close();
				} catch (IOException ex) {
					hideLoading();
					ex.printStackTrace();
				}
				uploadRecord(bos.toByteArray());
			}
			if (capre != null) {
				// 上传录像文件 (录像完成后点击上传首先上传录音3gp文件)
				Log.e("上传录像", "upload 录像");
				isSendVidio = true;
				
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buf = new byte[8 * 1024];
				try {
					CommonBody body = new CommonBody();
					body.setCommand(3);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					body.setFile("3gp");
					body.setBegin_index(0);
					String reqBody = gson.toJson(body);
					reqBody = reqBody + "\r\n\r\n";
					bos.write(reqBody.getBytes("ISO-8859-1"));
					FileInputStream fis = new FileInputStream(capre);// "/mnt/sdcard/atsmart/example.jpg");//
					// Bitmap bitmap = BitmapFactory.decodeStream(fis);
					// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					for (int readNum; (readNum = fis.read(buf)) != -1;) {
						if (bos.toByteArray().length < 100000) {
							bos.write(buf, 0, readNum);
							length += buf.length;
						} else {
							break;
						}
					}
					bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
					fis.close();
				} catch (IOException ex) {

					ex.printStackTrace();
				}
				Log.e("capre", "capre: = " + capre);
				//上传录像
				uploadVedio(bos.toByteArray());

			} else {
				im();
			}
		} catch (Exception e) {
			//e.printStackTrace();
		}
	}
	
	/**是否上传录音文件*/
	private boolean isSendVidio = false;
	
	private void uploadContent() {
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				Log.e("send", "send: = " + gson.toJson(uploadInfo));
				try{
				return ServiceHelper.getInstance().postData(
						ServiceHost.upload(), gson.toJson(uploadInfo),
						ResultInfo.class);
				}catch (Exception e) {
				}
				return null;
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealwithResult1(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					uploadContentByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void uploadContentByUrl2() {
		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				try {
					//
					Log.e("send", "send: = " + gson.toJson(uploadInfo));
					return ServiceHelper.getInstance().postData(
							ServiceHost.upload(), gson.toJson(uploadInfo),
							ResultInfo.class);

				} catch (Exception e) {
					//e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealwithResult1(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}
	
	private void uploadContentImg() {

		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				try{
				return ServiceHelper.getInstance().postData(
						ServiceHost.upload(), gson.toJson(uploadInfo),
						ResultInfo.class);
				}catch (Exception e) {
				}
				return null;
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealwithResult1(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				hideLoading();
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					uploadContentImgByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void uploadContentImgByUrl2() {

		new ServiceAsynTask<ResultInfo>() {

			@Override
			protected ResultInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				try{
				return ServiceHelper.getInstance().postData(
						ServiceHost.upload(), gson.toJson(uploadInfo),
						ResultInfo.class);
				}catch (Exception e) {
				}
				return null;
			}

			@Override
			protected void runWithResult(ResultInfo result) throws Exception {
				hideLoading();
				dealwithResult1(result);
			}

			@Override
			protected void runWithError(ResultInfo result, int iErrorCode)
					throws Exception {
				hideLoading();
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}
	// s
	private void dealwithResult1(ResultInfo result) {
		if (result == null || result.result != 0) {
			PrefsUtils.setUserState(String
					.valueOf(PersistentKeyUtil.UN_NORMAL_USER_STATE));
			new AlertDialog.Builder(context)
					.setTitle("汇报失败")
					.setMessage("是否保存且自动上传")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									try{
										CommonBody body = new CommonBody();
										body.setCommand(1);
										body.setImsi(BizApp.getInstance().getIMSI());
										body.setVersion(BizApp.getInstance()
												.getString(R.string.app_version));

										ShutDownSqlHelper psql = new ShutDownSqlHelper();
										psql.open(BizApp.getInstance()
												.getSqlHelper());
										PositionShutDownInfo pinfo = new PositionShutDownInfo();
										pinfo.setVer(gson.toJson(body));
										pinfo.setPos(gson.toJson(uploadInfo));
										if (reportType == 1) {
											String time = taskTime;
											String qti = "";
											if (time != null && time.length() > 10) {
												qti = time.substring(11,
														time.length());
											}
											if ("00:00:00.0".equals(qti)) {
												time = StringUtil
														.getFormTaskTime(taskTime);
											} else {
												time = StringUtil
														.getTaskTime(taskTime);
											}
											pinfo.setReportname(time + " "
													+ taskName + "(" + templateName
													+ ")");
										} else {
											pinfo.setReportname(templateName);
										}
										pinfo.setReporttype((reportType == 1 ? 3
												: PersistentKeyUtil.REPORT_TYPE_DIRECTLY));

										pinfo.setType(8);// 汇报错误，保存

										psql.addAttribute(pinfo);

										Intent intent = new Intent();
										intent.setClass(ReportActivity.this,
												LoginActivity.class);
										startActivity(intent);
										Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
										finish();
										dialog.dismiss();
									}catch (Exception e) {
										Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
										//e.printStackTrace();
									}
								}
							})
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							}).create().show();

		} else {
			PrefsUtils.setUserState(String
					.valueOf(PersistentKeyUtil.NORMAL_USER_STATE));
			ReportHistoryInfo history = new ReportHistoryInfo();
			if (reportType == 1) {
				tnsql.addAttribute(taskId, templateID);
				String time = taskTime;
				String qti = "";
				if (time != null && time.length() > 10) {
					qti = time.substring(11, time.length());
				}
				if ("00:00:00.0".equals(qti)) {
					time = StringUtil.getFormTaskTime(taskTime);
				} else {
					time = StringUtil.getTaskTime(taskTime);
				}
				history.name = time + " " + taskName + "(" + templateName + ")";

			} else {
				history.name = templateName;
			}
			history.date = StringUtil.getReportTime();
			history.type = (reportType == 1 ? 3
					: PersistentKeyUtil.REPORT_TYPE_DIRECTLY);
			BizApp.getInstance().getSqlHelper().addHistory(history);
			Toast.makeText(this, "汇报成功！", Toast.LENGTH_SHORT).show();
			detailInfo = null;
			PrefsUtils.setReportImagePath("");
			this.finish();
			return;
		}
	}

	@Override
	protected void onDestroy() {

		super.onDestroy();

	}

	// 上传录像
	private void uploadVedio(final byte[] bb) {

		new AsyncTask<Void, Void, ImgPathInfo>() {

			@Override
			protected ImgPathInfo doInBackground(Void... params) {
				try {
					Log.e("上传录像", "上传录像");
					return gson.fromJson(postOnService(bb), ImgPathInfo.class);
				} catch (Exception e) {
					isSendVidio = false;
//					Message message = new Message();
//					message.what = 0x002;
//					imgVidioHandler.sendMessage(message);
					//e.printStackTrace();
				}  
				return null;
			}

			protected void onPostExecute(ImgPathInfo result) {
				if(isSendVidio){
					dealWithResult(result, bb);
				}
			};
		}.execute();
	}

	// 录像返回处理
	private void dealWithResult(ImgPathInfo result, byte[] bb) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte[] buf = new byte[8 * 1024];
		try {
			CommonBody body = new CommonBody();
			body.setCommand(3);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(getString(R.string.app_version));
			if (result != null) {
				body.setFile(result.path);
				body.setBegin_index(length);
				String reqBody = gson.toJson(body);
				reqBody = reqBody + "\r\n\r\n";
				bos.write(reqBody.getBytes("ISO-8859-1"));
				FileInputStream fis = new FileInputStream(capre);// "/mnt/sdcard/atsmart/example.jpg");//
				// Bitmap bitmap = BitmapFactory.decodeStream(fis);
				// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				int cc = 0;
				for (; (fis.read(buf)) != -1;) {
					cc += buf.length;
				}
				// Log.e("length", String.valueOf(length));
				 Log.e("cc", "cc: = "+String.valueOf(cc) + " , length = " + String.valueOf(length));
				if (cc == length) {
					capre = null;
					UploadItemInfo itemInfo = new UploadItemInfo();
					itemInfo.id = vId;
					Log.e("上传录像", "id: = " + itemInfo.id);
					itemInfo.type = ITEM_TYPE_VIDEO;
					if (result != null) {
						itemInfo.value = result.path;
						Log.e("上传录像", "value: = " + itemInfo.value);
					}
					uploadInfo.items.add(itemInfo);
					Log.e("上传录像", "录像上传完成" + new Gson().toJson(uploadInfo));
					im();
					
				} else {
					fis = new FileInputStream(capre);
					long count = 0;
					for (int readNum; (readNum = fis.read(buf)) != -1;) {
						count += buf.length;
						if (count > length) {
							if (bos.toByteArray().length < 100000) {
								bos.write(buf, 0, readNum);
								length += buf.length;
							} else {
								break;
							}
						}

					}
					bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
					fis.close();
					Log.e("上传录像", "上传未完成继续上传");
					if(isSendVidio){
						uploadVedio(bos.toByteArray());
					}
				}
			} else {
				// Log.e("count", String.valueOf(count));
				count = count + 1;
				if (count >= 3) {
					tishi(bb);
				} else {
					if(isSendVidio){
						uploadVedio(bos.toByteArray());
					}
				}
			}

		} catch (IOException ex) {

			ex.printStackTrace();
		}
	}

	private void tishi(final byte[] bb) {
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (DialogInterface.BUTTON_POSITIVE == which) {
					uploadVedio(bb);
					count = 0;
				} else {
					capre = null;
					im();
				}
			}
		};
		
		DialogUtil.getAlertDialog(this, getString(R.string.alert_title),
				"当前网络信号较弱，是否继续？", getString(R.string.yes), listener,
				getString(R.string.no), listener).show();
	}

	private void uploadRecord(final byte[] bb) {

		new AsyncTask<Void, Void, ImgPathInfo>() {

			@Override
			protected ImgPathInfo doInBackground(Void... params) {
				try {
					return gson.fromJson(postOnService(bb), ImgPathInfo.class);
				} catch (MalformedURLException e) {
					//e.printStackTrace();
				} catch (IOException e) {
					//e.printStackTrace();
				} catch (BizException e) {
					//e.printStackTrace();
				}
				return null;
			}

			protected void onPostExecute(ImgPathInfo result) {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				byte[] buf = new byte[8 * 1024];
				try {
					CommonBody body = new CommonBody();
					body.setCommand(2);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					body.setFile(result.path);
					body.setBegin_index(re_length);
					String reqBody = gson.toJson(body);
					reqBody = reqBody + "\r\n\r\n";
					bos.write(reqBody.getBytes("ISO-8859-1"));
					FileInputStream fis = new FileInputStream(
							PrefsUtils.getReportRecordPath());// "/mnt/sdcard/atsmart/example.jpg");//
					// Bitmap bitmap = BitmapFactory.decodeStream(fis);
					// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
					int cc = 0;
					for (; (fis.read(buf)) != -1;) {
						cc += buf.length;
					}
					// Log.e("re_length", String.valueOf(re_length));
					// Log.e("cc", String.valueOf(cc));
					if (cc == re_length) {
						PrefsUtils.setReportRecordPath("");
						UploadItemInfo itemInfo = new UploadItemInfo();
						itemInfo.id = rId;
						itemInfo.type = ITEM_TYPE_RECORD;
						if (result != null) {
							itemInfo.value = result.path;
						}
						uploadInfo.items.add(itemInfo);
						if (capre == null) {
							im();
						} else {
							hideLoading();
						}
					} else {
						fis = new FileInputStream(
								PrefsUtils.getReportRecordPath());
						long count = 0;
						for (int readNum; (readNum = fis.read(buf)) != -1;) {
							count += buf.length;
							if (count > re_length) {
								if (bos.toByteArray().length < 100000) {
									bos.write(buf, 0, readNum);
									re_length += buf.length;
								} else {
									break;
								}
							}

						}
						bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
						fis.close();
						uploadRecord(bos.toByteArray());
					}

				} catch (IOException ex) {
					hideLoading();
					ex.printStackTrace();
				}
				PrefsUtils.setReportRecordPath("");
			};
		}.execute();
	}

	/*** 是否发送图片标志位 */
	private boolean isSendImg = true;

	private void im() {
		isSendImg = true;
		try {
			new Thread() {
				public void run() {
					if (hasImage
							&& !StringUtil.isEmptyOrNull(PrefsUtils
									.getReportImagePath())) {
						final String imageStr = PrefsUtils.getReportImagePath();
						String[] str = PrefsUtils.getReportImagePath().split(
								";");
						for (int i = 0; i < str.length; i++) {

							if (isSendImg) {
								final String[] str1 = str[i].split(",");
								final ByteArrayOutputStream bos = new ByteArrayOutputStream();
								byte[] buf = new byte[10 * 1024];
								try {
									CommonBody body = new CommonBody();
									body.setCommand(1);
									body.setImsi(BizApp.getInstance().getIMSI());
									body.setVersion(getString(R.string.app_version));
									body.setFile("jpg");
									body.setBegin_index(0);
									String reqBody = gson.toJson(body);
									Log.e("TAG", "body: = " + reqBody);
									reqBody = reqBody + "\r\n\r\n";
									bos.write(reqBody.getBytes("ISO-8859-1"));
									FileInputStream fis = new FileInputStream(
											str1[1]);// "/mnt/sdcard/atsmart/example.jpg");//
//									Log.e("TAG", "bos.size: = " + buf.length);
									for (int readNum; (readNum = fis.read(buf)) != -1;) {
										if (bos.toByteArray().length < 2000000) {
											bos.write(buf, 0, readNum);
											length += buf.length;
//											Log.e("TAG", "length: = " + length);
										} else {
											break;
										}
									}
									bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
									fis.close();
								} catch (IOException ex) {
									// isSendImg = false;
									ex.printStackTrace();
								}

								if ((i + 1) == str.length) {
									uploadImage(Integer.valueOf(str1[0]),
											bos.toByteArray(), true, imageStr);
								} else {
									uploadImage(Integer.valueOf(str1[0]),
											bos.toByteArray(), false, imageStr);

								}

							} else {
								break;
							}
						}

					} else {
						if (capre == null) {
							uploadContent();
						}
					}
				}
			}.start();
		} catch (Exception e) {

			//e.printStackTrace();
		}
	}

	ImgPathInfo result = null;

	private void uploadImage(final int ss, final byte[] bb, final boolean flag,
			final String imageStr) {
		try {
			result = gson.fromJson(postOnService(bb), ImgPathInfo.class);
		} catch (Exception e) {
			//e.printStackTrace();
			isSendImg = false;
		}
		delimg(result, ss, flag, imageStr);
	}


	/**汇报模板id*/
	private int report_ss;
	/**汇报图片组合字符串  模板id＋图片路径*/
	private String report_imageStr;
	private Handler imgVidioHandler = new Handler(){
		public void handleMessage(final Message msg) {
			super.handleMessage(msg);
			if (msg.what == 0x111) {
				final DialogInterface.OnClickListener li = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try{
//							CommonBody body = new CommonBody();
//							body.setCommand(1);
//							body.setImsi(BizApp.getInstance().getIMSI());
//							body.setVersion(BizApp.getInstance().getString(
//									R.string.app_version));

							ShutDownSqlHelper psql = new ShutDownSqlHelper();
							psql.open(BizApp.getInstance().getSqlHelper());
							PositionShutDownInfo pinfo = new PositionShutDownInfo();
							pinfo.setImagestr(report_imageStr);
							pinfo.setType(8);// 汇报错误，保存图片

							UploadItemInfo itemInfo = new UploadItemInfo();
							itemInfo.id = report_ss;
							itemInfo.type = ITEM_TYPE_IMAGEVIEW;
							itemInfo.value = "";
							uploadInfo.items.add(itemInfo);
							pinfo.setPos(new Gson().toJson(uploadInfo));

							if (reportType == 1) {
								String time = taskTime;
								String qti = "";
								if (time != null && time.length() > 10) {
									qti = time.substring(11, time.length());
								}
								if ("00:00:00.0".equals(qti)) {
									time = StringUtil.getFormTaskTime(taskTime);
								} else {
									time = StringUtil.getTaskTime(taskTime);
								}
								pinfo.setReportname(time + " " + taskName + "("
										+ templateName + ")");
							} else {
								pinfo.setReportname(templateName);
							}
							pinfo.setReporttype((reportType == 1 ? 3
									: PersistentKeyUtil.REPORT_TYPE_DIRECTLY));

							psql.addAttribute(pinfo);

							Intent intent = new Intent();
							intent.setClass(ReportActivity.this, LoginActivity.class);
							startActivity(intent);
							Toast.makeText(context, "保存成功", Toast.LENGTH_SHORT).show();
							finish();

							dialog.dismiss();
						}catch (Exception e) {
							Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
							//e.printStackTrace();
						}
						
					}
				};

				final DialogInterface.OnClickListener canli = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				};
				DialogUtil.getAlertDialog(ReportActivity.this,
						getString(R.string.report_error), "是否保存本地且自动上传",
						getString(R.string.yes), li, getString(R.string.no),
						canli).show();
			}

		};
	};
	
	//  
	private void delimg(ImgPathInfo result, final int ss, boolean flag,
			final String imageStr) {
		if (result == null) {
			hideLoading();
			isSendImg = false;
			report_ss = ss;
			report_imageStr = imageStr;
			
			Message msg = new Message();
			msg.what = 0x111;
			imgVidioHandler.sendMessage(msg);
			 
		} else {
			UploadItemInfo itemInfo = new UploadItemInfo();
			itemInfo.id = ss;
			itemInfo.type = ITEM_TYPE_IMAGEVIEW;
			if (result != null) {
				itemInfo.value = result.path;
			} else {
				itemInfo.value = "";
			}
			uploadInfo.items.add(itemInfo);

			if (flag) {
				uploadContentImg();
			}
		}
	}

	protected String postOnService(byte[] bb) throws MalformedURLException,
			IOException, BizException {
		HttpHelper http = new HttpHelper(bb.length);
		http.setCONNECTION_TIMEOUT(10000);
		http.setREAD_TIMEOUT(10000);
		try {
			http.createMode().url(ServiceHost.uploadImage())
					.header("Content-Type", "charset=ISO-8859-1")
					.header("Accept-Charset", "ISO-8859-1");
			// byte[] bb= reqBody.getBytes("ISO-8859-1");
			http.body(new ByteArrayInputStream(bb)).send();

		} catch (Exception ex) {
			if(PrefsUtils.getURL().equals(StringUtil.URL1)){
				PrefsUtils.setURL(StringUtil.URL2);
			}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
				PrefsUtils.setURL(StringUtil.URL1);
			}
			try{
				http.createMode().url(ServiceHost.uploadImage())
				.header("Content-Type", "charset=ISO-8859-1")
				.header("Accept-Charset", "ISO-8859-1");
				http.body(new ByteArrayInputStream(bb)).send();
			}catch (Exception e) {
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
			// Will not happen.
		}
		String bodyString = "";
		if (http.isSuccessful()) {
			bodyString = http.getBodyAsString();
			if (bodyString != null) {
				bodyString = bodyString.substring(
						bodyString.indexOf("\r\n\r\n"), bodyString.length());
				return bodyString;
			} else {
				return "";
			}
		} else {
			http.send();
			if (http.isSuccessful()) {
				bodyString = http.getBodyAsString();
				if (bodyString != null) {
					return bodyString;
				} else {
					return "";
				}
			}
			final int responseCode = http.getResponseCode();
			throw new BizException(responseCode);
		}
	}

	private List<byte[]> readImageAsByteArray(int con, String path, String str) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		List<byte[]> aa = new ArrayList<byte[]>();
		byte[] buf = new byte[8 * 1024];
		try {
			CommonBody body = new CommonBody();
			body.setCommand(con);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(getString(R.string.app_version));
			body.setFile(str);
			body.setBegin_index(0);
			String reqBody = gson.toJson(body);
			reqBody = reqBody + "\r\n\r\n";
			bos.write(reqBody.getBytes("ISO-8859-1"));
			FileInputStream fis = new FileInputStream(path);// "/mnt/sdcard/atsmart/example.jpg");//
			// Bitmap bitmap = BitmapFactory.decodeStream(fis);
			// bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			for (int readNum; (readNum = fis.read(buf)) != -1;) {
				if (bos.toByteArray().length < 100000) {
					bos.write(buf, 0, readNum);
				} else {
					aa.add(bos.toByteArray());
					body = new CommonBody();
					body.setCommand(con);
					body.setImsi(BizApp.getInstance().getIMSI());
					body.setVersion(getString(R.string.app_version));
					body.setFile(str);
					body.setBegin_index(bos.toByteArray().length);
					reqBody = gson.toJson(body);
					reqBody = reqBody + "\r\n\r\n";

					bos = new ByteArrayOutputStream();
					bos.write(reqBody.getBytes("ISO-8859-1"));
				}
			}
			bos.write("\r\n\r\n".getBytes("ISO-8859-1"));
			fis.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		// Log.e("bos", String.valueOf(bos.toByteArray().length));
		return aa;
	}

	private class TemplateID implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = -8517011347819302002L;
		@SuppressWarnings("unused")
		@SerializedName("template-id")
		public int id;
	}

	private class ImgPathInfo implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 7216739021733421705L;
		/**
		 *
		 */
		@SerializedName("file")
		public String path;
	}

	public class ImgInfo implements Serializable {
		/**
		 *
		 */
		private static final long serialVersionUID = 7216739021733421705L;
		/**
		 *
		 */
		@SerializedName("value")
		public String value;
	}

	/**
	 * 
	 * 初始化控件和UI视图
	 */

	private void initializeViews(final Button pickDate, final EditText showDate) {

		pickDate.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Message msg = new Message();

				if (pickDate.equals((Button) v)) {

					msg.what = ReportActivity.SHOW_DATAPICK;
					showDate111 = showDate;
				}

				ReportActivity.this.dateandtimeHandler.sendMessage(msg);

			}

		});

	}

	/*
	 * 初始化控件和UI视图
	 */

	private void initializeViewsTime(final Button pickTime,
			final EditText showTime) {

		pickTime.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Message msg = new Message();

				if (pickTime.equals((Button) v)) {

					msg.what = ReportActivity.SHOW_TIMEPICK;
					// msg.setData(data)
					showTime11 = showTime;
				}

				ReportActivity.this.dateandtimeHandler.sendMessage(msg);

			}

		});

	}

	/**
	 * 
	 * 设置日期
	 */

	private void setDateTime(EditText showTime) {

		final Calendar c = Calendar.getInstance();

		mYear = c.get(Calendar.YEAR);

		mMonth = c.get(Calendar.MONTH);

		mDay = c.get(Calendar.DAY_OF_MONTH);

		updateDateDisplay(showTime);

	}

	/**
	 * 
	 * 更新日期显示
	 */

	private void updateDateDisplay(EditText showDate) {

		showDate.setText(new StringBuilder().append(mYear).append("-")

		.append((mMonth + 1) < 10 ? "0" + (mMonth + 1) : (mMonth + 1))
				.append("-")

				.append((mDay < 10) ? "0" + mDay : mDay));

	}

	/**
	 * 
	 * 日期控件的事件
	 */

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,

		int dayOfMonth) {

			mYear = year;

			mMonth = monthOfYear;

			mDay = dayOfMonth;

			updateDateDisplay(showDate111);

		}

	};

	/**
	 * 
	 * 设置时间
	 */

	private void setTimeOfDay(EditText showTime) {

		final Calendar c = Calendar.getInstance();

		mHour = c.get(Calendar.HOUR_OF_DAY);

		mMinute = c.get(Calendar.MINUTE);

		updateTimeDisplay(showTime);

	}

	/**
	 * 
	 * 更新时间显示
	 */

	private void updateTimeDisplay(EditText showTime) {

		showTime.setText(new StringBuilder().append(mHour).append(":")

		.append((mMinute < 10) ? "0" + mMinute : mMinute));

	}

	/**
	 * 
	 * 时间控件事件
	 */

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			mHour = hourOfDay;

			mMinute = minute;

			updateTimeDisplay(showTime11);

		}

	};

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {

		case DATE_DIALOG_ID:

			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,

			mDay);

		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					true);

		}

		return null;

	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {

		switch (id) {

		case DATE_DIALOG_ID:

			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);

			break;

		case TIME_DIALOG_ID:

			((TimePickerDialog) dialog).updateTime(mHour, mMinute);

			break;

		}

	}

	/**
	 * 
	 * 处理日期和时间控件的Handler
	 */

	Handler dateandtimeHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {

			case ReportActivity.SHOW_DATAPICK:

				showDialog(DATE_DIALOG_ID);

				break;

			case ReportActivity.SHOW_TIMEPICK:

				showDialog(TIME_DIALOG_ID);

				break;

			}

		}

	};

	/**
	 * 拍照获取图片
	 */
	protected void doTakePhoto() {
		try {
			// Launch camera to take photo for selected contact
			if (!PHOTO_DIR.exists()) {
				PHOTO_DIR.mkdirs();
			}
			String FileName = System.currentTimeMillis() + ".jpg";
			mCurrentPhotoFile = new File(PHOTO_DIR, FileName);
			PrefsUtils.setImageFile(mCurrentPhotoFile.getAbsolutePath());
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} catch (ActivityNotFoundException e) {
			//e.printStackTrace();
			Toast.makeText(this, "photoPickerNotFoundText", Toast.LENGTH_LONG)
					.show();
		}
	}
	

	public static Intent getTakePickIntent(File f) {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}

	// // 封装请求Gallery的intent
	public static Intent getPhotoPickIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		return intent;
	}

	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
	// 
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.e("TAG===========", "requestCode: = " + requestCode + " , resultCode: = " + resultCode);
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
		case ITEM_TYPE_VIDEO:// 拍摄视频
			Uri uriVideo = data.getData();
			Cursor cursor = this.getContentResolver().query(uriVideo, null,
					null, null, null);
			if (cursor.moveToNext()) {
				/** _data：文件的绝对路径 ，_display_name：文件名 */
				capre = cursor.getString(cursor.getColumnIndex("_data"));
			}
			break;

		case PHOTO_PICKED_WITH_DATA:
			Bundle extras = data.getExtras();
			if (extras != null) {
				Bitmap bitmap = extras.getParcelable("data");
				if (bitmap == null) {
					Toast.makeText(this, "返回数据失败", Toast.LENGTH_LONG).show();
				}
				saveCamera(bitmap, false);
				if (chooseimage != null)
					chooseimage.setImageBitmap(bitmap);

				if (hasImage) {
					if (!StringUtil.isEmptyOrNull(PrefsUtils
							.getReportImagePath())) {
						String[] str = PrefsUtils.getReportImagePath().split(
								";");
						for (int i = 0; i < str.length; i++) {
							String[] str1 = str[i].split(",");
							Button aa = (Button) rootLayout
									.findViewById(Integer.valueOf(str1[0]));
							if (aa != null) {
								aa.setText("已完成拍照");
							}
						}

					}
				}
			}
			break;
		case CAMERA_WITH_DATA:
				if (mCurrentPhotoFile != null){
					doCropPhoto(mCurrentPhotoFile);
				}else{
					File ff= new File(PrefsUtils.getImageFile());
					doCropPhoto(ff);
				}
			break;
		case 321:
			try{
				Message msg = new Message();
				msg.what = 0x303;
				handler2.sendMessage(msg);
				new AsyncTask<Void, Void, Void>(){
					@Override
					protected Void doInBackground(Void... params) {
						try{
							File file = null;
							if (mCurrentPhotoFile != null){
								file = mCurrentPhotoFile;
							}else{
								File ff= new File(PrefsUtils.getImageFile());
								file = ff;
							}
							Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
							float scaleWidth = 1;
							float scaleHeight = 1;
							float scale = 1;
							Matrix matr = new Matrix();
							if(bm.getWidth() <= bm.getHeight()){
								if(bm.getWidth() > screen_width){
									scaleWidth = (float) screen_width/bm.getWidth();
								}
								if(bm.getHeight() > screen_height){
									scaleHeight = (float) screen_height / bm.getHeight();
								}
								if(scaleWidth != 1 && scaleHeight != 1){
									scale = scaleHeight >= scaleWidth ? scaleWidth : scaleHeight;
									matr.postScale(scale, scale);
								}else if(scaleWidth != 1 && scaleHeight == 1){
									scale = scaleWidth;
									matr.postScale(scale, scale);
								}else if(scaleHeight != 1 && scaleWidth == 1){
									scale = scaleHeight;
									matr.postScale(scale, scale);
								}else if(scaleWidth == 1 && scaleHeight == 1){
									scaleWidth = (float) screen_width/bm.getWidth();
									scaleHeight = (float) screen_height / bm.getHeight();
									matr.postScale(scaleWidth, scaleHeight);
								}
							}else if(bm.getWidth() > bm.getHeight()){
								if(bm.getWidth() > screen_height){
									scaleWidth = (float) screen_height/bm.getWidth();
								}
								if(bm.getHeight() > screen_width){
									scaleHeight = (float) screen_width / bm.getHeight();
								}
								if(scaleWidth != 1 && scaleHeight != 1){
									scale = scaleHeight >= scaleWidth ? scaleWidth : scaleHeight;
									matr.postScale(scale, scale);
								}else if(scaleWidth != 1 && scaleHeight == 1){
									scale = scaleWidth;
									matr.postScale(scale, scale);
								}else if(scaleHeight != 1 && scaleWidth == 1){
									scale = scaleHeight;
									matr.postScale(scale, scale);
								}else if(scaleWidth == 1 && scaleHeight == 1){
									scaleWidth = (float) screen_height/bm.getWidth();
									scaleHeight = (float) screen_width / bm.getHeight();
									matr.postScale(scaleWidth, scaleHeight);
								}
							}
							
							Bitmap bitmaps = null;
							bitmaps = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),bm.getHeight(), matr, true);
							try{
								if(bitmaps.getWidth() < screen_width && bitmaps.getHeight() < screen_height){
									Matrix matrs = new Matrix();
									float scaleWidths = (float) screen_width/bitmaps.getWidth();
									float scaleHeights = (float) screen_height / bitmaps.getHeight();
									matr.postScale(scaleWidths, scaleHeights);
									bitmaps = Bitmap.createBitmap(bitmaps, 0, 0, bitmaps.getWidth(),bitmaps.getHeight(), matrs, true);
								}
							}catch (Exception e) {
							}
							savetemCamera(bitmaps, false);
						}catch (Exception e) {
							Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show();
						}
						return null;
					}
					protected void onPostExecute(Void result) {
						Message msg = new Message();
						msg.what = 0x304;
						handler2.sendMessage(msg);
						if (!StringUtil.isEmptyOrNull(PrefsUtils.getImg())) {
							Intent intent = new Intent();
							intent.setClass(context, ShowPicActivity.class);
							startActivityForResult(intent, 322);
						}else{
							Toast.makeText(context, "图片保存失败", Toast.LENGTH_SHORT).show();
							return;
						}
					};
				}.execute();
			}catch(Exception ex){
				PrefsUtils.setImageFile(null);
				Message msg = new Message();
				msg.what = 0x304;
				handler2.sendMessage(msg);
				Toast.makeText(context, "图片拍摄异常", Toast.LENGTH_SHORT).show();
				return;
			}
			break;
		case 322:
			try{
				Bitmap bitmapssss = BitmapFactory.decodeFile(PrefsUtils.getImgs());
				if (bitmapssss == null) {
					Toast.makeText(this, "返回数据失败", Toast.LENGTH_SHORT).show();
				}else{
					Matrix mat = new Matrix();
					if(!StringUtil.isEmptyOrNull(PrefsUtils.getHaseRote())){
						mat.setRotate(-90);
					}
					float scaleWidth = 1;
					float scaleHeight = 1;
					float scale = 1;
					if(bitmapssss.getWidth() > 480 && bitmapssss.getHeight() > 480){
						scaleWidth = (float) 480 / bitmapssss.getWidth();
						scaleHeight = (float) 480 / bitmapssss.getHeight();
						scale = scaleHeight >= scaleWidth ? scaleWidth : scaleHeight;
						mat.postScale(scale, scale);
					}else if(bitmapssss.getWidth() > 480 && bitmapssss.getHeight() <= 480){
						scale = (float) 480/bitmapssss.getWidth();
						mat.postScale(scale, scale);
					}else if(bitmapssss.getWidth() <= 480 && bitmapssss.getHeight() > 480){
						scale = (float) 480/bitmapssss.getHeight();
						mat.postScale(scale, scale);
					}else if(bitmapssss.getWidth() <= 480 && bitmapssss.getHeight() <= 480){
						
					}
					
					Bitmap bitmapss= Bitmap.createBitmap(bitmapssss, 0, 0, bitmapssss.getWidth(),bitmapssss.getHeight(), mat, true);
					saveCamera(bitmapss, false);
					if (chooseimage != null)
						chooseimage.setImageBitmap(bitmapss);
	
					if (hasImage) {
						if (!StringUtil.isEmptyOrNull(PrefsUtils
								.getReportImagePath())) {
							String[] str = PrefsUtils.getReportImagePath().split(
									";");
							for (int i = 0; i < str.length; i++) {
								String[] str1 = str[i].split(",");
								Button aa = (Button) rootLayout
										.findViewById(Integer.valueOf(str1[0]));
								if (aa != null) {
									aa.setText("已完成拍照");
								}
							}
	
						}
					}
				}
			}catch(Exception ex){
				PrefsUtils.setImg(null);
				Toast.makeText(context, "保存图片异常", Toast.LENGTH_SHORT).show();
				return;
			}
			break;
		case 1023:
			if(!StringUtil.isEmptyOrNull(PrefsUtils.getImgs())){
				Bitmap bitmap = BitmapFactory.decodeFile(PrefsUtils.getImgs());
						if (bitmap == null) {
							Toast.makeText(this, "返回数据失败", Toast.LENGTH_LONG).show();
						}
						saveCamera(bitmap, false);
						if (chooseimage != null)
							chooseimage.setImageBitmap(bitmap);

						if (hasImage) {
							if (!StringUtil.isEmptyOrNull(PrefsUtils
									.getReportImagePath())) {
								String[] str = PrefsUtils.getReportImagePath().split(
										";");
								for (int i = 0; i < str.length; i++) {
									String[] str1 = str[i].split(",");
									Button aa = (Button) rootLayout
											.findViewById(Integer.valueOf(str1[0]));
									if (aa != null) {
										aa.setText("已完成拍照");
									}
								}

							}
						}
			}
			
			break;
		case 323:
			Bundle bundle = data.getExtras();
			String type = bundle.getString("type");
			final String value = bundle.getString("value");
			Log.e("TAG", "扫码返回 type: = " + type + " , value: = " + value);
			if(!StringUtil.isEmptyOrNull(value)){
				try{
				 new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(Void... params) {
						Message msg = new Message();
						msg.what = 0x303;
						handler2.sendMessage(msg);
						try{
						if(productSql != null ){
							ProductListInfo listInfo = productSql.getProduct();
							if(listInfo != null && listInfo.getProducts() != null){
								if(isql == null || isql.getCount() <= 0){
									for(ProductInfo info: listInfo.getProducts()){
										Item pageInfo = new Item();
										pageInfo.product_id = info.getProduct_id();
										ProductItemListInfo productItemListInfo = null;
										try{
										productItemListInfo	= ServiceHelper.getInstance().postData(
												ServiceHost.productitem(), new Gson().toJson(pageInfo),
												ProductItemListInfo.class);
										}catch (Exception e) {
											if(PrefsUtils.getURL().equals(StringUtil.URL1)){
												PrefsUtils.setURL(StringUtil.URL2);
											}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
												PrefsUtils.setURL(StringUtil.URL1);
											}
											
											try{
												productItemListInfo	= ServiceHelper.getInstance().postData(
														ServiceHost.productitem(), new Gson().toJson(pageInfo),
														ProductItemListInfo.class);
											}catch (Exception ex) {
												if(PrefsUtils.getURL().equals(StringUtil.URL1)){
													PrefsUtils.setURL(StringUtil.URL2);
												}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
													PrefsUtils.setURL(StringUtil.URL1);
												}
											}
										}
										if (productItemListInfo != null) {
											isql.deleteAttribute(info.getProduct_id());
											for (ProductItemInfo infoss : productItemListInfo.getProducts()) {
												isql.addProductItemInfo(infoss, info.getProduct_id());
											}
										}
									}
								}
							}
						}
						}catch (Exception e) {
						}
						return null;
					}
					@Override
					protected void onPostExecute(Void result) {
						Message msg = new Message();
						msg.what = 0x304;
						handler2.sendMessage(msg);
					
						if(isql != null){
							ProductItemInfo productItemInfo = isql.getProductItemInfo(value);
							if(productItemInfo != null){
								int pro = productItemInfo.getProduct_id();
								ProductListInfo proList = productSql.getProduct(pro);
								for(ProductInfo info: proList.getProducts()){
									if(info.getProduct_id() == pro){
										productEdit.setText(info.getName());
										if(proMap.containsKey(product_edit_item_id)){
											proMap.remove(product_edit_item_id);
										}
										proMap.put(product_edit_item_id, pro);
										break;
									}
								}
							}else{
								Toast.makeText(context, "查询结果为空", Toast.LENGTH_SHORT).show();
							}
						}else{
							Toast.makeText(context, "查询失败", Toast.LENGTH_SHORT).show();
						}
							
						super.onPostExecute(result);
					}}.execute();
				} catch (Exception e) {
				}
		}else{
			Toast.makeText(context, "扫描失败", Toast.LENGTH_SHORT).show();
		}
			
			break;
			default:break;
		}
	}
	
	public class Item implements Serializable {

		/**
		 *
		 */
		private static final long serialVersionUID = -6760611499805749529L;
		@SerializedName("product-id")
		public int product_id;
	}
	
	private Handler handler2 = new Handler(){
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x303){
				try{
					dialog.show();
				}catch (Exception e) {
				}
			}else if(msg.what == 0x304){
				try{
					dialog.cancel();
				}catch (Exception e) {
				}
			}
		};
	};

	protected void doCropPhoto(File f) {
		try {
//			 启动gallery去剪辑这个照片
//			final Intent intent = getCropImageIntent(Uri.fromFile(f));
//			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			Log.e("TAG", "doCropPhoto");
			Intent intent = new Intent();
			intent.putExtra("file", f.getAbsolutePath());
			intent.setClass(context, ShowPicActivity.class);
			startActivityForResult(intent, 1023);
		} catch (Exception e) {
			//e.printStackTrace();
			Toast.makeText(this, "失败", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序 剪裁后的图片跳转到新的界面
	 */
	public static Intent getCropImageIntent(Uri photoUri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 300);
		intent.putExtra("outputY", 300);
		intent.putExtra("return-data", true);
		return intent;
	}

	private void savetemCamera(Bitmap theBmp, boolean recycle) {
		byte[] data = null;
		try {
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			theBmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
			data = bytes.toByteArray();
			bytes.close();
			if (recycle)
				theBmp.recycle();
		} catch (Exception e) {
			// Log.e("imag", "保存图片异常");
			if (theBmp != null) {
				theBmp.recycle();
			}
			//e.printStackTrace();
		}
		theBmp = null;
		// make URI to save image
		SimpleDateFormat timeStampFormat = new SimpleDateFormat(
				"yyyyMMddhh_mm_ss");
		String filename = timeStampFormat.format(new Date());
		filename = filename + ".jpg";
		ContentValues values = new ContentValues();
		values.put(Media.TITLE, filename);
		values.put(Media.DISPLAY_NAME, filename);
		values.put(Media.DESCRIPTION, "Image capture by camera");
		values.put(Media.MIME_TYPE, "image/jpeg");

		String directory = BizApp.getInstance().getFilePath()+"/"+"tems"+"/";
		String filepath = directory + "/" + filename;
		values.put("_data", filepath);

		// Log.e("iamgeURL", "befor imageUri");
		imgUri = getContentResolver()
				.insert(Media.EXTERNAL_CONTENT_URI, values);
		// Log.e("iamgeURL", "after imageUri");

		try {
			OutputStream filoutputStream = getContentResolver()
					.openOutputStream(imgUri);
			filoutputStream.write(data);
			filoutputStream.flush();
			filoutputStream.close();

		} catch (Exception ex) {
			// Log.e("iamgeURL", "imagURL is error");
			imgUri = null;
			Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
		}
		data = null;
		System.gc();
		if(!StringUtil.isEmptyOrNull(PrefsUtils.getImg())){
			PrefsUtils.setImg(null);
		}
		PrefsUtils.setImg(filepath);
		 
	}
	
	 
	private void saveCamera(Bitmap theBmp, boolean recycle) {
		byte[] data = null;
		try {
			ByteArrayOutputStream bytes = new ByteArrayOutputStream();
			/**保存图片质量*/
			if(PrefsUtils.getIsHighPic() == null || StringUtil.isEmptyOrNull(PrefsUtils.getIsHighPic()) || PrefsUtils.getIsHighPic().equals("0")){
				theBmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
			}else if(PrefsUtils.getIsHighPic().equals("1")){
				theBmp.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
			}else if(PrefsUtils.getIsHighPic().equals("2")){
				theBmp.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
			}
			
			data = bytes.toByteArray();
			bytes.close();
			if (recycle)
				theBmp.recycle();
		} catch (Exception e) {
			if (theBmp != null) {
				theBmp.recycle();
			}
		}
		theBmp = null;
		// make URI to save image
		SimpleDateFormat timeStampFormat = new SimpleDateFormat(
				"yyyyMMddhh_mm_ss");
		String filename = timeStampFormat.format(new Date());
		filename = filename + ".jpg";
		ContentValues values = new ContentValues();
		values.put(Media.TITLE, filename);
		values.put(Media.DISPLAY_NAME, filename);
		values.put(Media.DESCRIPTION, "Image capture by camera");
		values.put(Media.MIME_TYPE, "image/jpeg");

		String directory = BizApp.getInstance().getFilePath()+"/"+"report";
		String filepath = directory + "/" + filename;
		values.put("_data", filepath);

		// Log.e("iamgeURL", "befor imageUri");
		imgUri = getContentResolver()
				.insert(Media.EXTERNAL_CONTENT_URI, values);
		// Log.e("iamgeURL", "after imageUri");

		try {
			OutputStream filoutputStream = getContentResolver()
					.openOutputStream(imgUri);
			filoutputStream.write(data);
			filoutputStream.flush();
			filoutputStream.close();

		} catch (Exception ex) {
			// Log.e("iamgeURL", "imagURL is error");
			imgUri = null;
			Toast.makeText(this, "", Toast.LENGTH_SHORT).show();
		}
		data = null;
		System.gc();

		int item_id = bundle.getInt(PersistentKeyUtil.TEMPLATE_ITEM_ID, 0);
		if (StringUtil.isEmptyOrNull(PrefsUtils.getReportImagePath())) {
			PrefsUtils.setReportImagePath(item_id + "," + filepath);
		} else {
			String[] str = PrefsUtils.getReportImagePath().split(";");
			StringBuffer sbf = new StringBuffer();
			boolean flag = false;
			for (int i = 0; i < str.length; i++) {
				if (str[i].indexOf(item_id + ",") != -1) {
					sbf.append(item_id + "," + filepath + ";");
					flag = true;
				} else {
					sbf.append(str[i] + ";");
				}
			}
			if (flag) {
				PrefsUtils.setReportImagePath(sbf.toString());
			} else {
				PrefsUtils.setReportImagePath(sbf.toString() + item_id + ","
						+ filepath);
			}
		}

		PrefsUtils.setReportImagePathOne(filepath);
	}

}
